package com.xucy.springboot.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @Author xucy
 * @Date 2019-09-01 11:05
 * @Description
 **/

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

//    @Autowired
//    private MyUserService myUserService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //设置基于内存的用户名密码登陆,前台输入用户名密码即可登陆
        //auth.inMemoryAuthentication().withUser("admin").password("12345").roles("ADMIN"); 不可用。需要对密码Bcrypt加密
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("admin").
                password(new BCryptPasswordEncoder().encode("12345")).roles("ADMIN");

//        //设置不同的角色
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("user").
                password(new BCryptPasswordEncoder().encode("12345")).roles("USER");

        //使用数据库存储的用户名密码登陆
//        auth.userDetailsService(myUserService).passwordEncoder(new MyPasswordEncoder());
//
//        //使用spring security 自带的user查询，但是需要表结构满足spring security users.ddl
//        auth.jdbcAuthentication().usersByUsernameQuery("").authoritiesByUsernameQuery("").passwordEncoder(new MyPasswordEncoder());


    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //如果是/person/**的路径，忽略验证。其他路径都需要登陆
        http.authorizeRequests()
                .antMatchers("/person/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .logout().permitAll()
                .and()
                .formLogin();
        http.csrf().disable();

    }

    @Override
    public void configure(WebSecurity web) throws Exception {

        web.ignoring().antMatchers("/js/**","/css/**");
    }
}
